<?php
namespace Framework\DiServices;

use GuzzleHttp\Psr7\Request;
use Http\Client\Curl\Client;
use Http\Message\MessageFactory\GuzzleMessageFactory;
use Http\Message\StreamFactory\GuzzleStreamFactory;

class HttpClient extends Client
{
    private $guzzleMessageFactory;

    public function __construct($curlTimeOut = 1000, $connectTimeOut = 100)
    {
        $guzzleMessageFactory = new GuzzleMessageFactory();

        $this->guzzleMessageFactory = $guzzleMessageFactory;

        parent::__construct($guzzleMessageFactory, new GuzzleStreamFactory(), [
            CURLOPT_TIMEOUT => $curlTimeOut,
            CURLOPT_CONNECTTIMEOUT => $connectTimeOut,
        ]);
    }

    public function sendGetRequest($url, array $bodyArray = [], array $header = [])
    {
        $request = $this->guzzleMessageFactory->createRequest('GET', $url, $header, json_encode($bodyArray));

        return $this->hookSendRequest($request, $bodyArray);
    }

    public function sendPostRequest($url, array $bodyArray = [], array $header = [])
    {
        $request = $this->guzzleMessageFactory->createRequest('POST', $url, $header, json_encode($bodyArray));

        return $this->hookSendRequest($request, $bodyArray);
    }

    public function sendPostRequestUrlEncode($url, array $bodyArray = [], $header = [])
    {
        $request = $this->guzzleMessageFactory->createRequest('POST', $url, $header, http_build_query($bodyArray));

        return $this->hookSendRequest($request, $bodyArray);
    }

    public function hookSendRequest(Request $request, $bodyArray = [])
    {
        try {
            $response = $this->sendRequest($request);
        } catch (\Exception $e) {
            throw $e;
        }
        return $response;
    }
}
